package cn.hznc.controller.service.inventory;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hznc.constant.CommonConstant;
import cn.hznc.domain.entity.*;
import cn.hznc.domain.request.inventory.*;
import cn.hznc.domain.response.PageResult;
import cn.hznc.exception.ToolLifeCycleEx;
import cn.hznc.exception.ToolLifeCycleException;
import cn.hznc.mapper.*;
import cn.hznc.repository.*;
import cn.hznc.utils.CommonUtil;
import cn.hznc.vo.*;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author：Administrator
 * @Date：2023/3/27 15:27
 */
@Service
@Slf4j
public class ToolPartsInventoryService {

    @Resource
    private ToolInventoryLocationRespository toolInventoryLocationRespository;

    @Resource
    private ToolInventoryLocationMapper toolInventoryLocationMapper;

    @Resource
    private ToolForkInfoMapper toolForkInfoMapper;

    @Resource
    private ToolPartMapper toolPartMapper;

    @Resource
    private ToolForkInfoRespository toolForkInfoRespository;

    @Resource
    private ToolPartService toolPartService;

//    @Resource
//    private InventoryLocationRespository inventoryLocationRespository;

    @Resource
    private WarehouseRespository warehouseRespository;

    @Autowired
    private ToolInventoryLocationHistoryService toolInventoryLocationHistoryService;

    @Resource
    private ToolInventoryLocationHistoryRepository toolInventoryLocationHistoryRepository;

    @Resource
    private InventoryLocationRespository inventoryLocationRespository;

    @Resource
    private AssemblyToolInventoryMapper assemblyToolInventoryMapper;

    @Resource
    private TypeItemMapper typeItemMapper;

    @Resource
    private InventoryLocationService inventoryLocationService;

    @Resource
    private ToolPartRespository toolPartRespository;

    @Autowired
    private MinioProp minioProp;

    public Map<String, Object> getToolPartsInventoryList(ToolPartsManageReq toolPartsManageReq) {
        Map<String, Object> retMap = new HashMap<>();
        List<ToolInventoryVo> resultList = toolInventoryLocationRespository.selectList(toolPartsManageReq);
        //设置库位所在仓库对应的库位数量以及库位的安全库存
        if (!CollectionUtils.isEmpty(resultList)) {
            resultList.forEach(this::buildToolInventoryVo);
            //按照安全库存过滤状态
            if (ObjectUtil.isNotNull(toolPartsManageReq.getLocationStatus())) {
                resultList = resultList.stream().filter(toolInventoryVo -> toolPartsManageReq.getLocationStatus().equals(toolInventoryVo.getStatus())).collect(Collectors.toList());
            }
        }
        //手动分页
        List<ToolInventoryVo> pageList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(resultList)) {
            pageList = CommonUtil.pageList(resultList, toolPartsManageReq.getPageNum(), toolPartsManageReq.getPageSize());
        }
        retMap.put("list", pageList);
        retMap.put("total", resultList.size());
        return retMap;
    }

    private void buildToolShelvesInventoryVo(ToolInventoryVo toolInventoryVo) {
        //图片地址拼接
        toolInventoryVo.setImage(minioProp.getBaseUrl() + minioProp.getBucketName() + "/" + toolInventoryVo.getImage());
        //设置库存中实际位置
        //toolInventoryVo.setLocationName(toolInventoryVo.getWarehouseName() +"库位编号：" + toolInventoryVo.getLocationNum());
        //设置库位安全库存
        WarehouseEntity warehouseEntity = warehouseRespository.getByIdOrName(toolInventoryVo.getWarehouseId(), "");
        String safetyInventoryConfigureParam = warehouseEntity.getSafetyInventoryConfigureParam();
        if (ObjectUtil.isNull(safetyInventoryConfigureParam) || safetyInventoryConfigureParam.equals("[]") || StringUtil.isEmpty(safetyInventoryConfigureParam)) {
            return;
        }
        JSONArray.parseArray(safetyInventoryConfigureParam, SingleWarehouseSafetyInventoryParam.class)
                .forEach(singleWarehouseSafetyInventoryParam -> {
                    if (Objects.equals(singleWarehouseSafetyInventoryParam.getPartno(), toolInventoryVo.getPartno())) {
                        toolInventoryVo.setSafetyInventory(singleWarehouseSafetyInventoryParam.getSafetyInventory());
                        if (toolInventoryVo.getSafetyInventory() >= toolInventoryVo.getPhysicalInventory()) {
                            toolInventoryVo.setStatus(0);
                        } else {
                            toolInventoryVo.setStatus(1);
                        }
                    }
                });
    }

    private void buildToolInventoryVo(ToolInventoryVo toolInventoryVo) {
        //图片地址拼接
        toolInventoryVo.setImage(minioProp.getBaseUrl() + minioProp.getBucketName() + "/" + toolInventoryVo.getImage());
        //设置库存中实际位置
        toolInventoryVo.setLocationName(toolInventoryVo.getWarehouseName() + "库位编号：" + toolInventoryVo.getLocationNum());
        InventoryLocationEntity inventoryLocationEntity = inventoryLocationRespository.getById(toolInventoryVo.getInventoryLocationId());
        String safetyInventoryConfigureParam = inventoryLocationEntity.getSafetyInventoryConfigureParam();
        if (ObjectUtil.isNull(safetyInventoryConfigureParam) || safetyInventoryConfigureParam.equals("[]")) {
            return;
        }
        //设置安全库存状态
        JSONArray.parseArray(safetyInventoryConfigureParam, SingleWarehouseSafetyInventoryParam.class)
                .forEach(singleWarehouseSafetyInventoryParam -> {
                    if (Objects.equals(singleWarehouseSafetyInventoryParam.getPartno(), toolInventoryVo.getPartno())) {
                        toolInventoryVo.setSafetyInventory(singleWarehouseSafetyInventoryParam.getSafetyInventory());
                        if (toolInventoryVo.getSafetyInventory() >= toolInventoryVo.getPhysicalInventory()) {
                            toolInventoryVo.setStatus(0);
                        } else {
                            toolInventoryVo.setStatus(1);
                        }
                    }
                });
//        if(ObjectUtil.isNotNull(toolInventoryVo.getSafetyInventory())){
//            if(toolInventoryVo.getSafetyInventory() >= toolInventoryVo.getPhysicalInventory()){
//                toolInventoryVo.setStatus(0);
//            }else{
//                toolInventoryVo.setStatus(1);
//            }
//        }
    }


    public Object getToolPartsDetailList(InventoryManageDetailReq inventoryManageDetailReq) {
        Map<String, Object> retMap = new HashMap<>();
        ToolForkInfoEntity toolForkInfoEntity = toolForkInfoMapper.selectById(inventoryManageDetailReq.getToolId());
        //类型基础信息
        retMap.put("toolForkInfo", toolForkInfoEntity);
        PageHelper.startPage(inventoryManageDetailReq.getPageNum(), inventoryManageDetailReq.getPageSize());
        PageInfo<EntryAndExitRecordVo> pageInfo = new PageInfo<>(toolInventoryLocationRespository.getEntryAndExitRecord(inventoryManageDetailReq));
        //出入库记录表
        retMap.put("recordList", pageInfo.getList());
        retMap.put("total", pageInfo.getTotal());
        //库存情况
        List<Map<String, Object>> inventoryStatus = toolInventoryLocationRespository.getLocationNum(inventoryManageDetailReq);
        inventoryStatus.forEach(stringIntegerMap -> {
            for (Map.Entry<String, Object> stringIntegerEntry : stringIntegerMap.entrySet()) {
                if (stringIntegerEntry.getKey().equals("warehouseName")) {
                    WarehouseEntity warehouseEntity = warehouseRespository.getByIdOrName(null, (String) stringIntegerMap.get(stringIntegerEntry.getKey()));
                    if (ObjectUtil.isNotNull(warehouseEntity)) {
                        String safetyInventoryConfigureParam = warehouseEntity.getSafetyInventoryConfigureParam();
                        if (StringUtil.isEmpty(safetyInventoryConfigureParam) || safetyInventoryConfigureParam.equals("[]")) {
                            return;
                        }
                        JSONArray.parseArray(safetyInventoryConfigureParam, SingleWarehouseSafetyInventoryParam.class)
                                .forEach(singleWarehouseSafetyInventoryParam -> {
                                    if (Objects.equals(singleWarehouseSafetyInventoryParam.getPartno(), toolForkInfoEntity.getPartno())) {
                                        stringIntegerMap.put("safetyInventory", singleWarehouseSafetyInventoryParam.getSafetyInventory());
                                    }
                                });
                    }
                }
            }
        });
        retMap.put("inventoryStatus", inventoryStatus);
        //刀具库存情况统计
        List<Map<String, Object>> inventorySnapshot = toolInventoryLocationHistoryService.getInventorySnapshot(inventoryManageDetailReq.getToolId(), inventoryManageDetailReq.getAssemblyToolId());
        Map<String, Object> nowDate = new HashMap<>();
        nowDate.put("date", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        nowDate.put("inventoryStatus", inventoryStatus);
        inventorySnapshot.add(nowDate);
        retMap.put("dateList", inventorySnapshot);
        return retMap;
    }

    public Object editLocationTool(EditLocationToolReq editLocationToolReq) {
        ToolInventoryLocationEntity toolInventoryLocationEntity = toolInventoryLocationMapper.selectById(editLocationToolReq.getId());
        if (ObjectUtil.isNotNull(toolInventoryLocationEntity)) {
            toolInventoryLocationEntity.setOal(editLocationToolReq.getOal());
            toolInventoryLocationEntity.setLength(editLocationToolReq.getLength());
            toolInventoryLocationMapper.updateById(toolInventoryLocationEntity);
        }
        return Boolean.TRUE;
    }

    public Object editLocationToolDetail(EditLocationToolReq editLocationToolReq) {
        ToolPartEntity toolPartEntity = toolPartMapper.selectById(editLocationToolReq.getId());
        if (ObjectUtil.isNotNull(toolPartEntity)) {
            toolPartEntity.setOal(editLocationToolReq.getOal());
            toolPartEntity.setLength(editLocationToolReq.getLength());
            toolPartMapper.updateById(toolPartEntity);
        }
        return Boolean.TRUE;
    }

    public Object getToolPartsManageShelvesList(ToolPartsManageReq toolPartsManageReq) {
        Map<String, Object> retMap = new HashMap<>();
        List<ToolInventoryVo> resultList = toolInventoryLocationRespository.getToolPartsManageShelvesList(toolPartsManageReq);
        //设置库位所在仓库对应的库位数量以及库位的安全库存
        if (!CollectionUtils.isEmpty(resultList)) {
            resultList.forEach(this::buildToolShelvesInventoryVo);
            //按照安全库存过滤状态
            if (ObjectUtil.isNotNull(toolPartsManageReq.getLocationStatus())) {
                List<ToolInventoryVo> filterList = new ArrayList<>();
                resultList.forEach(toolInventoryVo -> {
                    if (ObjectUtil.isNotNull(toolInventoryVo.getStatus()) && toolPartsManageReq.getLocationStatus() == toolInventoryVo.getStatus()) {
                        filterList.add(toolInventoryVo);
                    }
                });
                resultList = filterList;
            }
        }
        //手动分页
        List<ToolInventoryVo> pageList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(resultList)) {
            pageList = CommonUtil.pageList(resultList, toolPartsManageReq.getPageNum(), toolPartsManageReq.getPageSize());
        }
        retMap.put("list", pageList);
        retMap.put("total", resultList.size());
        return retMap;
    }

    public List<ToolInventoryVo> getToolPartsManageShelvesListReload(ToolPartsManageReq toolPartsManageReq) {
        List<ToolInventoryVo> resultList = toolInventoryLocationRespository.getToolPartsManageShelvesList(toolPartsManageReq);
        //PageHelper.startPage(toolPartsManageReq.getPageNum(), toolPartsManageReq.getPageSize());
        //PageInfo<ToolInventoryVo> pageInfo = new PageInfo<>(toolInventoryLocationRespository.getToolPartsManageShelvesList(toolPartsManageReq));
        //设置库位所在仓库对应的库位数量以及库位的安全库存
        if (!CollectionUtils.isEmpty(resultList)) {
            resultList.forEach(this::buildToolShelvesInventoryVo);
            //按照安全库存过滤状态
            if (ObjectUtil.isNotNull(toolPartsManageReq.getLocationStatus())) {
                resultList = resultList.stream().filter(toolInventoryVo -> toolPartsManageReq.getLocationStatus().equals(toolInventoryVo.getStatus())).collect(Collectors.toList());
            }
        }
        //手动分页
        return resultList;
    }

    public Object getToolPartsLocationDetail(InventoryManageDetailReq inventoryManageDetailReq) {
        Map<String, Object> retMap = new HashMap<>();
        ToolForkInfoEntity toolForkInfoEntity = toolForkInfoMapper.selectById(inventoryManageDetailReq.getToolId());
        //类型基础信息
        retMap.put("toolForkInfo", toolForkInfoEntity);
        //库位折线图信息
        //刀具库存情况统计
//        List<Map<String, Object>> inventorySnapshot = toolInventoryLocationHistoryService.getInventorySnapshot(inventoryManageDetailReq.getToolId(), inventoryManageDetailReq.getAssemblyToolId());
//        Map<String,Object> nowDate = new HashMap<>();
//        nowDate.put("date",new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
//        nowDate.put("inventoryStatus",inventoryStatus);
//        inventorySnapshot.add(nowDate);
        List<Map<String, Object>> inventorySnapshot = new ArrayList<>();
        List<String> dateList = toolInventoryLocationHistoryService.buildDateList();
        for (int i = dateList.size() - 2; i >= 0; i--) {
            Map<String, Object> locationInventoryStatusMap = new HashMap<>();
            Map<String, Integer> locationInventoryStatus = toolInventoryLocationHistoryRepository.locationInventoryStatus(dateList.get(i), toolForkInfoEntity.getId(), null, inventoryManageDetailReq.getInventoryLocationId());
            locationInventoryStatusMap.put("date", dateList.get(i + 1));
            locationInventoryStatusMap.put("inventoryStatus", locationInventoryStatus);
            inventorySnapshot.add(locationInventoryStatusMap);
        }
        Map<String, Object> nowDate = new HashMap<>();
        String currentDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        nowDate.put("date", currentDate);
        nowDate.put("inventoryStatus", toolInventoryLocationRespository.getlocationInventoryStatus(currentDate, toolForkInfoEntity.getId(), null, inventoryManageDetailReq.getInventoryLocationId()));
        inventorySnapshot.add(nowDate);
        retMap.put("dateList", inventorySnapshot);
        return retMap;
    }

    public Object editToolPartsSafetyStock(EditToolPartsSafetyStockReq editToolPartsSafetyStockReq) {
        ToolInventoryLocationEntity toolInventoryLocationEntity = toolInventoryLocationMapper.selectById(editToolPartsSafetyStockReq.getId());
        InventoryLocationEntity inventoryLocationEntity = inventoryLocationRespository.getById(toolInventoryLocationEntity.getInventoryLocationId());
        String safetyInventoryConfigureParam = inventoryLocationEntity.getSafetyInventoryConfigureParam();
        List<SingleWarehouseSafetyInventoryParam> existRecord = new ArrayList<SingleWarehouseSafetyInventoryParam>();
        if (StringUtil.isNotEmpty(safetyInventoryConfigureParam) || !"[]".equals(safetyInventoryConfigureParam)) {
            //安全库存配置不为空
            existRecord = JSONArray.parseArray(safetyInventoryConfigureParam, SingleWarehouseSafetyInventoryParam.class);
        }
        Boolean flag = Boolean.FALSE;
        //修改零件安全库存
        if (ObjectUtil.isNotNull(toolInventoryLocationEntity.getToolId())) {
            ToolForkInfoEntity toolForkInfoEntity = toolForkInfoMapper.selectById(toolInventoryLocationEntity.getToolId());
            if (CollectionUtil.isNotEmpty(existRecord)) {
                for (int i = 0; i < existRecord.size(); i++) {
                    SingleWarehouseSafetyInventoryParam singleWarehouseSafetyInventoryParam = existRecord.get(i);
                    if (toolForkInfoEntity.getPartno().equals(singleWarehouseSafetyInventoryParam.getPartno())) {
                        //该库位有安全库存配置且有该类型的安全库存配置
                        singleWarehouseSafetyInventoryParam.setSafetyInventory(editToolPartsSafetyStockReq.getSafetyInventory());
                        flag = Boolean.TRUE;
                        break;
                    }
                }
            }
            if (!flag) {
                SingleWarehouseSafetyInventoryParam singleWarehouseSafetyInventoryParam = new SingleWarehouseSafetyInventoryParam();
                singleWarehouseSafetyInventoryParam.setPartno(toolForkInfoEntity.getPartno());
                singleWarehouseSafetyInventoryParam.setSafetyInventory(editToolPartsSafetyStockReq.getSafetyInventory());
                if (CollectionUtil.isEmpty(existRecord)) {
                    existRecord = new ArrayList<SingleWarehouseSafetyInventoryParam>();
                }
                existRecord.add(singleWarehouseSafetyInventoryParam);
            }
            //修改总成安全库存
        } else if (ObjectUtil.isNotNull(toolInventoryLocationEntity.getAssemblyToolInventoryId())) {
            Boolean flag1 = Boolean.FALSE;
            AssemblyToolInventoryEntity assemblyToolInventoryEntity = assemblyToolInventoryMapper.selectById(toolInventoryLocationEntity.getAssemblyToolInventoryId());
            if (CollectionUtil.isNotEmpty(existRecord)) {
                for (int i = 0; i < existRecord.size(); i++) {
                    SingleWarehouseSafetyInventoryParam singleWarehouseSafetyInventoryParam = existRecord.get(i);
                    if (assemblyToolInventoryEntity.getToolNo().equals(singleWarehouseSafetyInventoryParam.getToolNo())) {
                        //该库位有安全库存配置且有该类型的安全库存配置
                        singleWarehouseSafetyInventoryParam.setSafetyInventory(editToolPartsSafetyStockReq.getSafetyInventory());
                        flag1 = Boolean.TRUE;
                        break;
                    }
                }
            }
            if (!flag1) {
                SingleWarehouseSafetyInventoryParam singleWarehouseSafetyInventoryParam = new SingleWarehouseSafetyInventoryParam();
                singleWarehouseSafetyInventoryParam.setToolNo(assemblyToolInventoryEntity.getToolNo());
                singleWarehouseSafetyInventoryParam.setSafetyInventory(editToolPartsSafetyStockReq.getSafetyInventory());
                if (CollectionUtil.isEmpty(existRecord)) {
                    existRecord = new ArrayList<SingleWarehouseSafetyInventoryParam>();
                }
                existRecord.add(singleWarehouseSafetyInventoryParam);
            }
        }
        inventoryLocationEntity.setSafetyInventoryConfigureParam(JSONObject.toJSONString(existRecord));
        inventoryLocationRespository.updateById(inventoryLocationEntity);
        return Boolean.TRUE;
    }
//    @Transactional
//    public PageResult<ToolInventoryVo> queryAllToolPart(ToolConsumptionandUsageAnalysisReq toolConsumptionandUsageAnalysisReq){
//
//        List<Integer> inventoryLocationIds = inventoryLocationRespository.selectLocationIdByLocationNum(toolConsumptionandUsageAnalysisReq);
//
////        PageHelper.startPage(toolConsumptionandUsageAnalysisReq.getPageNo(), toolConsumptionandUsageAnalysisReq.getPageSize());
//        LambdaQueryWrapper<ToolPartEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//        if (CollectionUtil.isNotEmpty(inventoryLocationIds)){
//            lambdaQueryWrapper.in(ToolPartEntity::getInventoryLocationId,inventoryLocationIds);
//        }
//        if (StringUtil.isNotEmpty(toolConsumptionandUsageAnalysisReq.getQueryCondition())){
//            lambdaQueryWrapper.and(wrapper ->{
//                wrapper.like(ToolPartEntity::getPartno,toolConsumptionandUsageAnalysisReq.getQueryCondition())
//                        .or()
//                        .like(ToolPartEntity::getToolNo,toolConsumptionandUsageAnalysisReq.getQueryCondition())
//                        .or()
//                        .like(ToolPartEntity::getIdnr,toolConsumptionandUsageAnalysisReq.getQueryCondition())
//                        .or()
//                        .like(ToolPartEntity::getUniqueId,toolConsumptionandUsageAnalysisReq.getQueryCondition());
//            });
////            lambdaQueryWrapper.or().like(ToolPartEntity::getPartno,toolConsumptionandUsageAnalysisReq.getQueryCondition());
////            lambdaQueryWrapper.or().like(ToolPartEntity::getToolNo,toolConsumptionandUsageAnalysisReq.getQueryCondition());
////            lambdaQueryWrapper.or().like(ToolPartEntity::getIdnr,toolConsumptionandUsageAnalysisReq.getQueryCondition());
////            lambdaQueryWrapper.or().like(ToolPartEntity::getUniqueId,toolConsumptionandUsageAnalysisReq.getQueryCondition());
//        }
//        if (toolConsumptionandUsageAnalysisReq.getTypeFlag() == 1){
//            lambdaQueryWrapper.ne(ToolPartEntity::getPartno,"");
////            lambdaQueryWrapper.and(wreapper->{
////                wreapper.ne(ToolPartEntity::getPartno,"");});
//        }else if (toolConsumptionandUsageAnalysisReq.getTypeFlag() == 0){
//            lambdaQueryWrapper.ne(ToolPartEntity::getToolNo,"");
////            lambdaQueryWrapper.and(wreapper->{
////                        wreapper.ne(ToolPartEntity::getToolNo,"");});
//
//        }
//        if (ObjectUtil.isNotNull(toolConsumptionandUsageAnalysisReq.getCodeScannerFlag())){
//            if(toolConsumptionandUsageAnalysisReq.getCodeScannerFlag() == 0 ){
//                lambdaQueryWrapper.and(queryWrapper -> queryWrapper.eq(ToolPartEntity::getCodeScannerFlag,0).or().isNull(ToolPartEntity::getCodeScannerFlag));
//            } else if (toolConsumptionandUsageAnalysisReq.getCodeScannerFlag() == 1) {
//                lambdaQueryWrapper.eq(ToolPartEntity::getCodeScannerFlag,1);
//            }
//            //lambdaQueryWrapper.eq(ToolPartEntity::getCodeScannerFlag,toolConsumptionandUsageAnalysisReq.getCodeScannerFlag());
//        }
//        List<ToolPartEntity> toolPartEntityList = toolPartMapper.selectList(lambdaQueryWrapper);
//        List<ToolInventoryVo> toolInventoryVoList = new ArrayList<>();
//        if (CollectionUtil.isNotEmpty(toolPartEntityList)){
//            toolPartEntityList.forEach(toolPartEntity -> {
//                ToolInventoryVo toolInventoryVo = new ToolInventoryVo();
//                toolInventoryVo.setWarehouseName(buildLocationName(toolPartEntity.getInventoryLocationId()));
//                if (ObjectUtil.isNotEmpty(toolPartEntity.getInventoryLocationId())){
//                    toolInventoryVo.setInventoryLocationId(toolPartEntity.getInventoryLocationId());
//                }
//                if (StringUtil.isNotEmpty(toolPartEntity.getUniqueId()))
//                    toolInventoryVo.setUniqueId(toolPartEntity.getUniqueId());
//                if (StringUtil.isNotEmpty(toolPartEntity.getIdnr()))
//                    toolInventoryVo.setIdnr(toolPartEntity.getIdnr());
//                if (StringUtil.isNotEmpty(toolPartEntity.getPartno())){
//                    toolInventoryVo.setPartno(toolPartEntity.getPartno());
//                    toolInventoryVo.setType("刀具");
//                }else if(StringUtil.isNotEmpty(toolPartEntity.getToolNo())){
//                    toolInventoryVo.setType("总成");
//                    toolInventoryVo.setToolNo(toolPartEntity.getToolNo());
//                }
//                if (StringUtil.isNotEmpty(toolPartEntity.getImage())){
//                    String img = minioProp.getBaseUrl() + minioProp.getBucketName() + "/" +toolPartEntity.getImage();
//                    toolInventoryVo.setImage(img);
//                }
//                if (StringUtil.isNotEmpty(toolPartEntity.getToolType())){
//                    toolInventoryVo.setTypeName(typeItemMapper.getTypeNameByType(toolPartEntity.getToolType()));
//                }
//                toolInventoryVo.setCodeScannerFlag(toolPartEntity.getCodeScannerFlag());
//                toolInventoryVoList.add(toolInventoryVo);
//            });
//        }
////        if (toolConsumptionandUsageAnalysisReq.getTypeFlag() == 0){
////            toolInventoryVoList.removeIf(o->o.getType().equals("刀具"));
////        }else if (toolConsumptionandUsageAnalysisReq.getTypeFlag() == 1){
////            toolInventoryVoList.removeIf(o->o.getType().equals("总成"));
////        }
//        PageInfo<ToolInventoryVo> result = new PageInfo<>(CommonUtil.pageList(toolInventoryVoList,toolConsumptionandUsageAnalysisReq.getPageNo(),toolConsumptionandUsageAnalysisReq.getPageSize()));
////        PageInfo<ToolInventoryVo> result = new PageInfo<>(toolInventoryVoList);
//        return new PageResult<>(result.getList(), (long)toolInventoryVoList.size());
//    }

    @Transactional
    public PageResult<ToolPartEntity> queryAllToolPart(QueryAllToolPartReq queryAllToolPartReq) {
        //设置locationIds
        if(ObjectUtil.isNotNull(queryAllToolPartReq.getWarehouseSearchId()) || StringUtils.isNotBlank(queryAllToolPartReq.getWarehouseSearchTypes()) || StringUtils.isNotBlank(queryAllToolPartReq.getLocationSearchId())){
            queryAllToolPartReq.setLocationIds(inventoryLocationRespository.selectLocationIds(queryAllToolPartReq));
        }
        PageHelper.startPage(queryAllToolPartReq.getPageNum() , queryAllToolPartReq.getPageSize());
        PageInfo<ToolPartEntity> pageInfo = new PageInfo<>(toolPartRespository.qryAllToolParts(queryAllToolPartReq));
        if(CollectionUtil.isNotEmpty(pageInfo.getList())){
            pageInfo.getList().forEach(toolPartEntity -> {
                toolPartEntity.setWarehouseName(buildLocationName(toolPartEntity.getInventoryLocationId()));
            });
        }
        return new PageResult<>(pageInfo.getList() , pageInfo.getTotal());
    }

    public String buildLocationName(Integer id) {
        LocationNameVo locationNameVo = inventoryLocationRespository.queryLocationById(id);
        if (locationNameVo != null) {
            StringBuilder stringBuilder = new StringBuilder();
            String locationName = stringBuilder.append(locationNameVo.getTypeName()).append("-")
                    .append(locationNameVo.getWarehouseName()).append("-库位")
                    .append(locationNameVo.getLocationNum()).append("-位置").append(locationNameVo.getRow())
                    .append("-").append(locationNameVo.getColumn()).toString();
            return locationName;
        } else {
            return "未分配库位";

        }
    }

    //    @Transactional
//    public PageResult<ToolInventoryVo> queryAllToolPart1(ToolConsumptionandUsageAnalysisReq toolConsumptionandUsageAnalysisReq){
//
//        List<Integer> inventoryLocationIds = inventoryLocationRespository.selectLocationIdByLocationNum(toolConsumptionandUsageAnalysisReq);
//
////        PageHelper.startPage(toolConsumptionandUsageAnalysisReq.getPageNo(), toolConsumptionandUsageAnalysisReq.getPageSize());
//        LambdaQueryWrapper<ToolPartEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//        if (CollectionUtil.isNotEmpty(inventoryLocationIds)){
//            lambdaQueryWrapper.in(ToolPartEntity::getInventoryLocationId,inventoryLocationIds);
//        }
//        if (StringUtil.isNotEmpty(toolConsumptionandUsageAnalysisReq.getQueryCondition())){
//            lambdaQueryWrapper.and(wrapper ->{
//                wrapper.eq(ToolPartEntity::getPartno,toolConsumptionandUsageAnalysisReq.getQueryCondition())
//                        .or()
//                        .eq(ToolPartEntity::getToolNo,toolConsumptionandUsageAnalysisReq.getQueryCondition())
//                        .or()
//                        .eq(ToolPartEntity::getIdnr,toolConsumptionandUsageAnalysisReq.getQueryCondition())
//                        .or()
//                        .eq(ToolPartEntity::getUniqueId,toolConsumptionandUsageAnalysisReq.getQueryCondition());
//            });
////            lambdaQueryWrapper.or().like(ToolPartEntity::getPartno,toolConsumptionandUsageAnalysisReq.getQueryCondition());
////            lambdaQueryWrapper.or().like(ToolPartEntity::getToolNo,toolConsumptionandUsageAnalysisReq.getQueryCondition());
////            lambdaQueryWrapper.or().like(ToolPartEntity::getIdnr,toolConsumptionandUsageAnalysisReq.getQueryCondition());
////            lambdaQueryWrapper.or().like(ToolPartEntity::getUniqueId,toolConsumptionandUsageAnalysisReq.getQueryCondition());
//        }
//        if (toolConsumptionandUsageAnalysisReq.getTypeFlag() == 1){
//            lambdaQueryWrapper.ne(ToolPartEntity::getPartno,"");
//            lambdaQueryWrapper.eq(ToolPartEntity::getSelectedFlag , 0);
////            lambdaQueryWrapper.and(wreapper->{
////                wreapper.ne(ToolPartEntity::getPartno,"");});
//        }else if (toolConsumptionandUsageAnalysisReq.getTypeFlag() == 0){
//            lambdaQueryWrapper.ne(ToolPartEntity::getToolNo,"");
//            lambdaQueryWrapper.eq(ToolPartEntity::getSelectedFlag , 0);
////            lambdaQueryWrapper.and(wreapper->{
////                        wreapper.ne(ToolPartEntity::getToolNo,"");});
//
//        }
//        List<ToolPartEntity> toolPartEntityList = toolPartMapper.selectList(lambdaQueryWrapper);
//        List<ToolInventoryVo> toolInventoryVoList = new ArrayList<>();
//        if (CollectionUtil.isNotEmpty(toolPartEntityList)){
//            toolPartEntityList.forEach(toolPartEntity -> {
//                ToolInventoryVo toolInventoryVo = new ToolInventoryVo();
//                LocationNameVo locationNameVo = inventoryLocationRespository.queryLocation(toolPartEntity.getId());
//                if (locationNameVo != null){
//                    StringBuilder stringBuilder = new StringBuilder();
//                    String locationName = stringBuilder.append(locationNameVo.getTypeName()).append("-")
//                            .append(locationNameVo.getWarehouseName()).append("-库位")
//                            .append(locationNameVo.getLocationNum()).append("-位置").append(locationNameVo.getRow())
//                            .append("-").append(locationNameVo.getColumn()).toString();
//                    toolInventoryVo.setWarehouseName(locationName);
//                }else{
//                    toolInventoryVo.setWarehouseName("未分配库位");
//
//                }
//                if (ObjectUtil.isNotEmpty(toolPartEntity.getInventoryLocationId())){
//                    toolInventoryVo.setInventoryLocationId(toolPartEntity.getInventoryLocationId());
//                }
//                if (StringUtil.isNotEmpty(toolPartEntity.getUniqueId()))
//                    toolInventoryVo.setUniqueId(toolPartEntity.getUniqueId());
//                if (StringUtil.isNotEmpty(toolPartEntity.getIdnr()))
//                    toolInventoryVo.setIdnr(toolPartEntity.getIdnr());
//                if (StringUtil.isNotEmpty(toolPartEntity.getPartno())){
//                    toolInventoryVo.setPartno(toolPartEntity.getPartno());
//                    toolInventoryVo.setType("刀具");
//                }else if(StringUtil.isNotEmpty(toolPartEntity.getToolNo())){
//                    toolInventoryVo.setType("总成");
//                    toolInventoryVo.setToolNo(toolPartEntity.getToolNo());
//                }
//                if (StringUtil.isNotEmpty(toolPartEntity.getImage())){
//                    String img = minioProp.getBaseUrl() + minioProp.getBucketName() + "/" +toolPartEntity.getImage();
//                    toolInventoryVo.setImage(img);
//                }
//                if (StringUtil.isNotEmpty(toolPartEntity.getToolType())){
//                    toolInventoryVo.setTypeName(typeItemMapper.getTypeNameByType(toolPartEntity.getToolType()));
//                }
//                toolInventoryVoList.add(toolInventoryVo);
//            });
//        }
////        if (toolConsumptionandUsageAnalysisReq.getTypeFlag() == 0){
////            toolInventoryVoList.removeIf(o->o.getType().equals("刀具"));
////        }else if (toolConsumptionandUsageAnalysisReq.getTypeFlag() == 1){
////            toolInventoryVoList.removeIf(o->o.getType().equals("总成"));
////        }
//        PageInfo<ToolInventoryVo> result = new PageInfo<>(CommonUtil.pageList(toolInventoryVoList,toolConsumptionandUsageAnalysisReq.getPageNo(),toolConsumptionandUsageAnalysisReq.getPageSize()));
////        PageInfo<ToolInventoryVo> result = new PageInfo<>(toolInventoryVoList);
//        return new PageResult<>(result.getList(), (long)toolInventoryVoList.size());
//    }
////    private Map<String,String> stringToMap(String s){
////        s = s.substring(2,s.length()-2);
////        s.replaceAll("\"","");
////        String[] strs = s.split(",");
////        Map<String,String> map = new HashMap<>();
////        for (String s1 : strs){
////            String key = s1.split(":")[0];
////            key = key.substring(1,key.length()-1);
////            String value = "";
////            try {
////                value = s1.split(":")[1].replaceAll("\"","");
////            }catch (Exception e){
////            }
////            map.put(key,value);
////        }
////        return map;
////    }
//
    @Transactional
    public void updateLocation(UpdateLocationVo updateLocationVo) throws ToolLifeCycleException {
        ToolInventoryVo toolInventoryVo = updateLocationVo.getToolInventoryVo();
        if (toolInventoryVo.getType().equals("刀具")) {
            LambdaQueryWrapper<ToolPartEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(ToolPartEntity::getUniqueId, toolInventoryVo.getUniqueId());
            ToolPartEntity toolPartEntity = toolPartMapper.selectOne(lambdaQueryWrapper);
            if (toolInventoryVo.getInventoryLocationId() != 0) {
                InBoundOrOutBoundReq inBoundOrOutBoundReq = new InBoundOrOutBoundReq();
                inBoundOrOutBoundReq.setInventoryLocationId(toolInventoryVo.getInventoryLocationId());
                inBoundOrOutBoundReq.setPartno(toolInventoryVo.getPartno());
                inBoundOrOutBoundReq.setNumber(1);
                inBoundOrOutBoundReq.setOperator(updateLocationVo.getOperator());
                inventoryLocationService.outboundLocationTool(inBoundOrOutBoundReq);
            }
            List<ToolPartEntity> toolPartEntityList = new ArrayList<>();
            toolPartEntityList.add(toolPartEntity);
            InboundToolReq inboundToolReq = new InboundToolReq();
            inboundToolReq.setOperator(updateLocationVo.getOperator());
            inboundToolReq.setNumber(1);
            inboundToolReq.setPartno(toolInventoryVo.getPartno());
            inboundToolReq.setLocationId(updateLocationVo.getNewInventoryLocationId());
            inboundToolReq.setInboundTools(toolPartEntityList);
            inventoryLocationService.inboundUniqueTool(inboundToolReq);
        } else if (toolInventoryVo.getType().equals("总成")) {
            LambdaQueryWrapper<AssemblyToolInventoryEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(AssemblyToolInventoryEntity::getToolNo, toolInventoryVo.getToolNo());
            List<AssemblyToolInventoryEntity> assemblyToolInventoryEntity = assemblyToolInventoryMapper.selectList(lambdaQueryWrapper);
            if (toolInventoryVo.getInventoryLocationId() != 0) {
                OutBoundAssemblyReq outBoundAssemblyReq = new OutBoundAssemblyReq();
                outBoundAssemblyReq.setOperator(updateLocationVo.getOperator());
                outBoundAssemblyReq.setNumber(1);
                outBoundAssemblyReq.setInventoryLocationId(toolInventoryVo.getInventoryLocationId());
                outBoundAssemblyReq.setAssemblyToolInventoryId(assemblyToolInventoryEntity.get(0).getId());
                inventoryLocationService.outboundLocationAssemblyTool(outBoundAssemblyReq);
            }
            InboundAssemblyReq inboundAssemblyReq = new InboundAssemblyReq();
            inboundAssemblyReq.setLocationId(updateLocationVo.getNewInventoryLocationId());
            inboundAssemblyReq.setOperator(updateLocationVo.getOperator());
            inboundAssemblyReq.setNumber(1);
            inboundAssemblyReq.setAssemblyUniqueId(toolInventoryVo.getUniqueId());
            inventoryLocationService.inboundUniqueAssemblyTool(inboundAssemblyReq);

        }

    }

    public Object queryNoManagementToolPart(ToolPartsManageReq toolPartsManageReq) {
        PageHelper.startPage(toolPartsManageReq.getPageNum(), toolPartsManageReq.getPageSize());
        PageInfo<ToolPartNoManagementVo> pageInfo = new PageInfo<>(toolPartRespository.queryNoManagementToolPart(toolPartsManageReq));
        if(CollectionUtil.isNotEmpty(pageInfo.getList())){
            pageInfo.getList().forEach(toolPartNoManagementVo -> {
                toolPartNoManagementVo.setPartType(toolForkInfoRespository.selectPartTypeByPartno(toolPartNoManagementVo.getPartno()));
            });
        }
        return new PageResult<>(pageInfo.getList(), pageInfo.getTotal());
    }

    public Object queryNoManagementToolParts(NoManagementReq noManagementReq) {
        PageHelper.startPage(noManagementReq.getPageNum(), noManagementReq.getPageSize());
        PageInfo<ToolPartEntity> pageInfo = new PageInfo<>(toolPartRespository.queryNoManagementToolParts(noManagementReq));
        return new PageResult<>(pageInfo.getList(), pageInfo.getTotal());
    }

    public Object qryAllToolPart(QryAllToolPartReq qryAllToolPartReq) {
        List<ToolPartEntity> toolPartEntities = toolPartRespository.qryAllToolPart(qryAllToolPartReq);
        if (CollectionUtil.isNotEmpty(toolPartEntities)) {
            toolPartEntities.forEach(toolPartEntity -> {
                toolPartEntity.setWarehouseName(buildLocationName(toolPartEntity.getInventoryLocationId()));
            });
        }
        return toolPartEntities;
    }

    public Object qryAssemblyToolByShankRfid(String shankRfid) {
        if (StringUtil.isEmpty(shankRfid)) {
            return new ToolPartEntity();
        }
        ToolPartEntity toolPartEntity = toolPartRespository.getByUniqueId(shankRfid);
        if (ObjectUtil.isNotNull(toolPartEntity)) {
            ToolPartEntity assemblyEntity = toolPartRespository.getByUniqueId(toolPartEntity.getAssemblyToolUniqueId());
            if(ObjectUtil.isNull(assemblyEntity)){
                return new ToolPartEntity();
            }
            assemblyEntity.setShankRfid(shankRfid);
            assemblyEntity.setWarehouseName(buildLocationName(assemblyEntity.getInventoryLocationId()));
            return assemblyEntity;
        }
        return null;
    }

    public Object unbindingAssemblyTool(UnbindingAssemblyToolReq unbindingAssemblyToolReq) throws ToolLifeCycleException {
        if(StringUtil.isEmpty(unbindingAssemblyToolReq.getRfid()) || StringUtil.isEmpty(unbindingAssemblyToolReq.getToolRfid()) || StringUtil.isEmpty(unbindingAssemblyToolReq.getShankRfid())){
            return Boolean.FALSE;
        }
        List<ToolPartEntity> updateList = new ArrayList<>();
        ToolPartEntity assemblyTool = toolPartService.getByUniqueId(unbindingAssemblyToolReq.getRfid());
        ToolPartEntity tool = toolPartService.getByUniqueId(unbindingAssemblyToolReq.getToolRfid());
        ToolPartEntity shank = toolPartService.getByUniqueId(unbindingAssemblyToolReq.getShankRfid());
        if((ObjectUtil.isNotNull(tool)&&tool.getIsAssembled()==0)||(ObjectUtil.isNotNull(shank)&&shank.getIsAssembled()==0)){
            return Boolean.FALSE;
        }
        String operator = unbindingAssemblyToolReq.getOperator();
        //判断是否需要出库
        if(ObjectUtil.isNotNull(unbindingAssemblyToolReq.getLocationId()) && unbindingAssemblyToolReq.getLocationId()>=0){
            //返回异常提示
            //throw  new ToolLifeCycleException(ToolLifeCycleEx.NEED_OUTBOUND.getCode(), ToolLifeCycleEx.NEED_OUTBOUND.getMsg());
            //进行自动出库
            UniqueAssemblyToolVo uniqueAssemblyToolVo = new UniqueAssemblyToolVo();
            uniqueAssemblyToolVo.setUniqueId(unbindingAssemblyToolReq.getRfid());
            uniqueAssemblyToolVo.setId(assemblyTool.getId());
            uniqueAssemblyToolVo.setInventoryLocationId(assemblyTool.getInventoryLocationId());
            uniqueAssemblyToolVo.setToolNo(assemblyTool.getToolNo());
            OutboundUniqueAssemblyReq outboundUniqueAssemblyReq = new OutboundUniqueAssemblyReq();
            outboundUniqueAssemblyReq.setOperator(unbindingAssemblyToolReq.getOperator());
            outboundUniqueAssemblyReq.setBatchAssemblyTool(Arrays.asList(uniqueAssemblyToolVo));
            try {
                inventoryLocationService.outboundUniqueAssemblyTool(outboundUniqueAssemblyReq);
            } catch (ToolLifeCycleException e) {
                log.error(e.getCode(), e.getMsg());
            }
        }
        //生成报废日志
        buildDamageLog(assemblyTool , operator);
        //进行解绑
        assemblyTool.setInventoryLocationId(0);
        assemblyTool.setParams("");
        assemblyTool.setIsDamage(1);
        assemblyTool.setDamageTime(new Date());
        updateList.add(assemblyTool);
        toolPartService.buildUnAssembleLog(assemblyTool , operator);
        unbindingToolPart(updateList , tool , operator);
        unbindingToolPart(updateList , shank , operator);
        if(CollectionUtil.isNotEmpty(updateList)){
            toolPartMapper.updateBatchById(updateList);
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    @Transactional
    public Object unbindingAssemblyToolReload(String rfid , List<String> originalToolRfids , List<String> newToolRfids , List<String> originalShankRfids , List<String> newShankRfids , Integer locationId , String operator) throws ToolLifeCycleException {
        if(StringUtil.isEmpty(rfid)){
            throw new ToolLifeCycleException(ToolLifeCycleEx.TOOL_UNIQUE_ID_NO_EXIST.getCode() , ToolLifeCycleEx.TOOL_UNIQUE_ID_NO_EXIST.getMsg());
        }
        List<ToolPartEntity> updateList = new ArrayList<>();
        ToolPartEntity assemblyTool = toolPartService.getByUniqueId(rfid);
        List<ToolPartEntity> toolList = toolPartService.getByUniqueIds(originalToolRfids);
        List<ToolPartEntity> shankList = toolPartService.getByUniqueIds(originalShankRfids);
        checkIsAssemble(toolList);
        checkIsAssemble(shankList);
        //判断是否需要出库
        if(ObjectUtil.isNotNull(locationId) && locationId>=0){
            //返回异常提示
            //throw  new ToolLifeCycleException(ToolLifeCycleEx.NEED_OUTBOUND.getCode(), ToolLifeCycleEx.NEED_OUTBOUND.getMsg());
            //进行自动出库
            UniqueAssemblyToolVo uniqueAssemblyToolVo = new UniqueAssemblyToolVo();
            uniqueAssemblyToolVo.setUniqueId(rfid);
            uniqueAssemblyToolVo.setId(assemblyTool.getId());
            uniqueAssemblyToolVo.setInventoryLocationId(assemblyTool.getInventoryLocationId());
            uniqueAssemblyToolVo.setToolNo(assemblyTool.getToolNo());
            OutboundUniqueAssemblyReq outboundUniqueAssemblyReq = new OutboundUniqueAssemblyReq();
            outboundUniqueAssemblyReq.setOperator(operator);
            outboundUniqueAssemblyReq.setBatchAssemblyTool(Arrays.asList(uniqueAssemblyToolVo));
            try {
                inventoryLocationService.outboundUniqueAssemblyTool(outboundUniqueAssemblyReq);
            } catch (ToolLifeCycleException e) {
                log.error(e.getCode(), e.getMsg());
            }
        }
        //校验是否全拆
        if(CollectionUtil.isNotEmpty(newToolRfids) && CollectionUtil.isNotEmpty(newShankRfids)){
            if(!isSameContent(originalToolRfids , newToolRfids) || !isSameContent(originalShankRfids , newShankRfids)){
                //TODO 只换部分
                replacePart(rfid , originalToolRfids , newToolRfids , originalShankRfids , newShankRfids , locationId , operator);
                return Boolean.TRUE;
            }
        }
        //生成报废日志
        buildDamageLog(assemblyTool , operator);
        //进行解绑
        assemblyTool.setInventoryLocationId(0);
        assemblyTool.setParams("");
        assemblyTool.setIsDamage(1);
        assemblyTool.setDamageTime(new Date());
        updateList.add(assemblyTool);
        toolPartService.buildUnAssembleLog(assemblyTool , operator);
        if(CollectionUtil.isNotEmpty(toolList)){
            toolList.forEach(tool->unbindingToolPart(updateList , tool , operator));
        }
        if(CollectionUtil.isNotEmpty(shankList)){
            shankList.forEach(shank->unbindingToolPart(updateList , shank , operator));
        }
        if(CollectionUtil.isNotEmpty(updateList)){
            toolPartMapper.updateBatchById(updateList);
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    private void replacePart(String rfid, List<String> originalToolRfids, List<String> newToolRfids, List<String> originalShankRfids, List<String> newShankRfids, Integer locationId, String operator) throws ToolLifeCycleException {
        List<ToolPartEntity> updateList = new ArrayList<>();
        ToolPartEntity originalAssemblyTool = toolPartRespository.getByUniqueId(rfid);
        if(ObjectUtil.isNull(originalAssemblyTool)){
            throw new ToolLifeCycleException(ToolLifeCycleEx.INVENTORY_DATA_EXCEPTION.getCode(), ToolLifeCycleEx.INVENTORY_DATA_EXCEPTION.getCode());
        }
        Map<String , List<String>> paramsMap = new HashMap<>();
        paramsMap.put("toolType" ,newToolRfids);
        paramsMap.put("shankType" ,newShankRfids);
        originalAssemblyTool.setParams(JSONArray.toJSONString(paramsMap));
        updateList.add(originalAssemblyTool);
        //获取拆除的零件列表以及绑定的零件列表
        List<String> unbindingList = new ArrayList<>();
        List<String> bindingList = new ArrayList<>();
        for (String originalToolRfid : originalToolRfids) {
            //新列表中不包含的就是拆下来的
            if(StringUtils.isNotBlank(originalToolRfid) && !newToolRfids.contains(originalToolRfid)){
                unbindingList.add(originalToolRfid);
            }
        }
        for (String originalShankRfid : originalShankRfids) {
            //新列表中不包含的就是拆下来的
            if(StringUtils.isNotBlank(originalShankRfid) && !newShankRfids.contains(originalShankRfid)){
                unbindingList.add(originalShankRfid);
            }
        }
        for (String newToolRfid : newToolRfids) {
            //旧列表中不包含的就是组装的
            if(StringUtils.isNotBlank(newToolRfid) && !originalToolRfids.contains(newToolRfid)){
                bindingList.add(newToolRfid);
            }
        }
        for (String newShankRfid : newShankRfids) {
            //旧列表中不包含的就是组装的
            if(StringUtils.isNotBlank(newShankRfid) && !originalShankRfids.contains(newShankRfid)){
                bindingList.add(newShankRfid);
            }
        }
        //进行解绑操作
        if(CollectionUtil.isNotEmpty(unbindingList)){
            List<ToolPartEntity> unbindingUniqueIds = toolPartService.getByUniqueIds(unbindingList);
            for (ToolPartEntity toolPartEntity : unbindingUniqueIds) {
                unbindingList.forEach(toolPartRfid -> unbindingToolPart(updateList , toolPartEntity , operator));
            }
        }
        //进行部分绑定操作
        if(CollectionUtil.isNotEmpty(bindingList)){
            List<ToolPartEntity> bindingUniqueIds = toolPartService.getByUniqueIds(bindingList);
            for (ToolPartEntity toolPartEntity : bindingUniqueIds) {
                unbindingList.forEach(toolPartRfid -> bindingToolPart(updateList , toolPartEntity , rfid , operator));
            }
        }
    }


    private void checkIsAssemble(List<ToolPartEntity> toolPartEntities) throws ToolLifeCycleException{
        if(CollectionUtil.isNotEmpty(toolPartEntities)){
            for (ToolPartEntity toolPartEntity : toolPartEntities) {
                if(ObjectUtil.isNotNull(toolPartEntity) && toolPartEntity.getIsAssembled() != 1){
                    throw new ToolLifeCycleException(ToolLifeCycleEx.TOOL_PART_DATA_ERROR.getCode() , ToolLifeCycleEx.TOOL_PART_DATA_ERROR.getMsg());
                }
            }
        }
    }

    public boolean isSameContent(List<String> originalUniqueIds , List<String> newUniqueIds){
        if(originalUniqueIds.equals(newUniqueIds)){
            return true;
        }
        if(originalUniqueIds.size() != newUniqueIds.size()){
            return false;
        }
        for (int i = 0; i < originalUniqueIds.size(); i++) {
            String s1 = originalUniqueIds.get(i);
            String s2 = newUniqueIds.get(i);

            if(StringUtils.isBlank(s1) &&StringUtils.isBlank(s2)){
                continue;
            }

            if(StringUtils.isBlank(s1) || StringUtils.isBlank(s2) || !s1.equals(s2)){
                return false;
            }
        }
        return true;
    }

    private void buildDamageLog(ToolPartEntity assemblyTool, String operator) {
        AssemblyDamageLogVo assemblyDamageLogVo = new AssemblyDamageLogVo();
        assemblyDamageLogVo.setOperator(operator);
        assemblyDamageLogVo.setType(CommonConstant.DAMAGE);
        assemblyDamageLogVo.setCreateTime(new Date());
        if(StringUtil.isEmpty(assemblyTool.getDamageLog()) || "[]".equals(assemblyTool.getDamageLog())){
            //之前无装配记录
            List<AssemblyDamageLogVo> list = new ArrayList<>();
            list.add(assemblyDamageLogVo);
            assemblyTool.setDamageLog(JSONArray.toJSONString(list));
            return;
        }
        //之前有装配记录
        List<AssemblyDamageLogVo> assemblyDamageLogVos = JSONArray.parseArray(assemblyTool.getDamageLog(), AssemblyDamageLogVo.class);
        assemblyDamageLogVos.add(assemblyDamageLogVo);
        assemblyTool.setDamageLog(JSONArray.toJSONString(assemblyDamageLogVos));
    }

    private void unbindingToolPart(List<ToolPartEntity> updateList, ToolPartEntity tool, String operator) {
        toolPartService.buildUnAssembleLog(tool , operator);
        tool.setIsAssembled(0);
        tool.setInventoryLocationId(0);
        tool.setAssemblyToolUniqueId("");
        updateList.add(tool);
    }

    private void bindingToolPart(List<ToolPartEntity> updateList, ToolPartEntity tool,String assemblyToolRfid  , String operator) {
        toolPartService.buildAssembleLog(tool , operator);
        tool.setIsAssembled(1);
        tool.setInventoryLocationId(-1);
        tool.setAssemblyToolUniqueId("");
        updateList.add(tool);
    }

    public Object queryStatusByLocationId(Integer locationId) {
        Integer status = inventoryLocationRespository.queryStatusByLocationId(locationId);
        return ObjectUtil.isNotNull(status)? status:0;
    }

    public Object queryStatusByLocationIdReload(Integer locationId) {
        Integer status = inventoryLocationRespository.queryStatusByLocationId(locationId);
        return ObjectUtil.isNotNull(status)? status:0;
    }

    public Object qryByRfid(String rfid) {
        QueryWrapper<ToolPartEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("unique_id" , rfid);
        ToolPartEntity toolPartEntity = toolPartMapper.selectOne(wrapper);
        if(ObjectUtil.isNotNull(toolPartEntity)){
            toolPartEntity.setWarehouseName(buildLocationName(toolPartEntity.getInventoryLocationId()));
        }
        return toolPartEntity;
    }

    public Object updateToolPartFlag() {
        QueryWrapper<ToolPartEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("type_flag" , 0);
        List<ToolPartEntity> toolPartEntities = toolPartMapper.selectList(wrapper);
        if(CollectionUtil.isNotEmpty(toolPartEntities)){
            toolPartEntities.forEach(toolPartEntity -> {
                //根据零件类型设置标志位
                String toolType = toolPartEntity.getToolType();
                if(StringUtils.isNotBlank(toolType)){
                    if(toolType.startsWith("A001B001")){
                        toolPartEntity.setToolPartFlag(1);
                    }else if(toolType.startsWith("A001B002")){
                        toolPartEntity.setToolPartFlag(2);
                    } else if (toolType.startsWith("A001B003")) {
                        toolPartEntity.setToolPartFlag(3);
                    }
                }
            });
        }
        toolPartMapper.updateBatchById(toolPartEntities);
        return Boolean.TRUE;
    }

    public Object updateToolPartLifeRate() {
        QueryWrapper<ToolPartEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("type_flag" , 0);
        List<ToolPartEntity> toolPartEntities = toolPartMapper.selectList(wrapper);
        List<ToolPartEntity> updateList = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(toolPartEntities)){
            for (ToolPartEntity toolPartEntity : toolPartEntities) {
                if(StringUtils.isBlank(toolPartEntity.getTimeUsage()) || StringUtils.isBlank(toolPartEntity.getLife())){
                    toolPartEntity.setRemainingLifeRate((long)100);
                    updateList.add(toolPartEntity);
                }else{
                    String toolLife = toolPartEntity.getLife();
                    String timeUsage = toolPartEntity.getTimeUsage();
                    if(toolLife.equals("0h")){
                        toolPartEntity.setRemainingLifeRate((long)100);
                        updateList.add(toolPartEntity);
                    }else{
                         Integer toolLifeInt = Integer.valueOf(toolLife.substring(0, toolLife.length() - 1));
                         Double timeUsageDouble = Double.valueOf(timeUsage.substring(0 , timeUsage.length() - 1));
                         toolPartEntity.setRemainingLifeRate(Math.round((toolLifeInt - timeUsageDouble)/toolLifeInt *100));
                    }
                }
            }
        }
        if(CollectionUtil.isNotEmpty(updateList)){
            //toolPartMapper.updateBatchById(updateList);
            for (int i = 0; i < 200; i++) {
                List<ToolPartEntity> subInsertList = updateList.stream().skip(i * 600).limit(600).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(subInsertList)) {
                    toolPartMapper.updateBatchById(subInsertList);
                }
            }
        }
        return Boolean.TRUE;
    }

    public Object deletePartOfToolInventoryData() {
        List<Integer> locationIds = inventoryLocationRespository.selectLocationIdsReload("A001" , null , null);
        QueryWrapper<ToolInventoryLocationEntity> wrapper = new QueryWrapper<>();
        List<ToolInventoryLocationEntity> delete1List = new ArrayList<>();
        List<ToolPartEntity> delete2List = new ArrayList<>();
        wrapper.isNotNull("tool_id");
        List<Integer> filterToolIdList = buildFilterToolIdList();
        wrapper.notIn("tool_id" , filterToolIdList);
        wrapper.in("inventory_location_id" , locationIds);
        List<ToolInventoryLocationEntity> toolForkInfoEntities = toolInventoryLocationMapper.selectList(wrapper);
        if(CollectionUtil.isNotEmpty(toolForkInfoEntities)){
            toolForkInfoEntities.forEach(toolInventoryLocationEntity -> {
                List<ToolPartEntity> toolPartEntities = toolPartRespository.selectlistByLocationIdAndToolId(toolInventoryLocationEntity.getInventoryLocationId() , toolInventoryLocationEntity.getToolId());
                delete2List.addAll(toolPartEntities);
            });
        }
        delete1List.addAll(toolForkInfoEntities);
        if(CollectionUtil.isNotEmpty(delete1List)){
            toolInventoryLocationMapper.deleteBatchIds(delete1List);
        }
        if(CollectionUtil.isNotEmpty(delete2List)){
            toolInventoryLocationMapper.deleteBatchIds(delete2List);
        }
        return toolForkInfoEntities;
    }

    private List<Integer> buildFilterToolIdList() {
        List<Integer> resultList = new ArrayList<>();
        resultList.add(126816);
        resultList.add(130902);
        resultList.add(116718);
        resultList.add(123197);
        resultList.add(122522);
        resultList.add(130899);
        resultList.add(130901);
        resultList.add(118981);
        resultList.add(116483);
        resultList.add(131195);
        return resultList;
    }
}
